package db;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class DBUtil {

	private static final String URL = "jdbc:mysql://127.0.0.1:3306/student";
	private static final String USER = "root";
	private static final String PASSWORD = "123456";

	private static Connection conn = null;
	
	//静态块
	static {
		try {
			//1.加载数据库驱动
			Class.forName("com.mysql.jdbc.Driver");

			//2.获取数据库的连接
			conn = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		return conn;
	}


	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		//连接数据库的步骤
		//1.加载数据库驱动
		Class.forName("com.mysql.jdbc.Driver");

		//2.获取数据库的连接
		Connection conn = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);

		//3.通过数据库的连接操作数据库，实现增删改查
		Statement stmt = (Statement) conn.createStatement();
		ResultSet rs = stmt.executeQuery("SELECT id,name,age FROM information");

		System.out.println("学生姓名\t学号\t年龄");
		while(rs.next()) {
			System.out.println(rs.getString("name") + "\t" + rs.getInt(1) + "\t" + rs.getInt(3));
		}
	}

}
